package com.cssy.xxkj.logic.service.impl;

import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.xxkj.basic.dao.BasicProductBomMaterialsDAO;
import com.cssy.xxkj.basic.dao.BasicProductBomProcessDAO;
import com.cssy.xxkj.basic.entity.*;
import com.cssy.xxkj.basic.service.IBasicMaterialsBomService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.dao.*;
import com.cssy.xxkj.logic.entity.InOutBillDO;
import com.cssy.xxkj.logic.entity.LogicExcelToStoreDO;
import com.cssy.xxkj.logic.entity.LogicWarehouseHistoryDO;
import com.cssy.xxkj.logic.entity.LogicWhCheckTaskDO;
import com.cssy.xxkj.logic.entity.vo.*;
import com.cssy.xxkj.logic.service.*;
import com.cssy.xxkj.logic.util.OftenMapUtil;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("excelExportService")
public class ExcelExportServiceImpl implements IExcelExportService {

	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	@Resource(name="excelExportDAO")
	private ExcelExportDAO excelExportDAO;

	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;
	@Resource(name="logicProductionDispatchingService")
	private ILogicProductionDispatchingService logicProductionDispatchingService;

	@Resource(name = "logicReportsUtilService")
	private ILogicReportsUtilService logicReportsUtilService;

	@Resource(name = "oftenMapUtil")
	private OftenMapUtil oftenMapUtil;

	@Resource(name = "logicExcelToStoreService")
	private ILogicExcelToStoreService logicExcelToStoreService;

	@Resource(name = "logicWarehouseHistoryDAO")
	private LogicWarehouseHistoryDAO logicWarehouseHistoryDAO;

	@Resource(name = "logicProductionStorageOutService")
	private ILogicProductionStorageOutService logicProductionStorageOutService;

	@Resource(name="basicMaterialsBomService")//bam
	private IBasicMaterialsBomService basicMaterialsBomService;

	@Resource(name="basicProductBomMaterialsDAO")//bom 物品
	private BasicProductBomMaterialsDAO basicProductBomMaterialsDAO;

	@Resource(name = "basicUtilService")
	private IBasicUtilService basicUtilService;

	@Resource(name="basicProductBomProcessDAO")
	private BasicProductBomProcessDAO basicProductBomProcessDAO;

	@Resource(name="logicWhCheckTaskItemDAO")
    private LogicWhCheckTaskItemDAO logicWhCheckTaskItemDAO;

	@Resource(name = "logicWarehouseBatchInService")
	private ILogicWarehouseBatchInService logicWarehouseBatchInService;

	@Resource(name = "logicWarehouseBatchInItemDAO")
	private LogicWarehouseBatchInItemDAO logicWarehouseBatchInItemDAO;

	//出入库明细表
	@Resource(name = "logicWarehouseDetailsService")
	private ILogicWarehouseDetailsService logicWarehouseDetailsService;

	@Resource(name = "logicWhCheckTaskDAO")//盘点信息
	private LogicWhCheckTaskDAO logicWhCheckTaskDAO;

	//重写月末库存汇总
	public List<LogicWarehouseEndMonthSumVO> findEndMonth(HttpServletRequest request)throws SyBaseException{
		List<LogicWarehouseEndMonthSumVO> endMonth=new ArrayList<LogicWarehouseEndMonthSumVO>();
		try {
			//查询仓库
			String whCode = request.getParameter("whCode");
			if(StringUtils.isBlank(whCode)){
				return endMonth;
			}
			//日期
			String dateStr=request.getParameter("date");
			if(StringUtils.isBlank(dateStr.trim())){
				return endMonth;
			}

			Map<String, LogicWarehouseEndMonthSumVO> endMonthMap= new HashMap<String, LogicWarehouseEndMonthSumVO>();
			Map<String , BasicStorageInfoTestDO> storageMap=oftenMapUtil.getStroageInfoMapKeyCode(new SearchConditions());
			Map<String , BasicStorageInfoTypeTestDO> tMap=oftenMapUtil.getStorageType();
			Map<String , Map<String, LogicWhCheckTaskDO>> ctwhMap=this.getCtWhMap(request);//获取每个仓库的当前选择时间的盘点的期初 期末
			//判断是否有期初、期末
			Map<String, LogicWhCheckTaskDO> checkTaskMap = ctwhMap.get(whCode);
			if(checkTaskMap==null||checkTaskMap.isEmpty()){
				return endMonth;
			}
			//没有期末
			if(checkTaskMap.get("end")==null){
				return endMonth;
			}
			//期初数据
			LogicWhCheckTaskDO qcCheckTask = checkTaskMap.get("start");
			this.getBeforDate(request, endMonthMap, storageMap, tMap, qcCheckTask);
			//出入库
			this.getMiddleData(request, endMonthMap,storageMap,tMap,ctwhMap);
			//期末数据
			this.getEndDate(request, endMonthMap, storageMap, tMap, whCode, dateStr);
			/*endMonthMap=this.getBeforDate(request, endMonthMap,storageMap,tMap,ctwhMap);//期初数据
			endMonthMap=this.getMiddleData(request, endMonthMap,storageMap,tMap,ctwhMap);//出入库数据
			endMonthMap=this.getEndDate(request,endMonthMap,storageMap,tMap,ctwhMap);//获取期末的数据
*/			Map<String , BasicMaterialsDO>  materials=oftenMapUtil.getMaterialMapByCode(this.getClearCondition());
			Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeById(this.getClearCondition());//类别
			Map<String , BasicMaterialsTypeDO> materialsSeries=oftenMapUtil.getMaterialTypeKeyMaterialCodeCodition(this.getClearCondition(),materials);//系列
			endMonth=this.getEndDateForListEndVO(endMonth, endMonthMap, materials,materialsType, materialsSeries);
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(e);
		}
		return endMonth;
	}
	/**
	 * 数据填充
	 * @param endMonth
	 * @param endMonthMap
	 * @param materials
	 * @param materialsType
	 * @param materialsSeries
	 * @return
	 * @throws Exception
	 */
	private List<LogicWarehouseEndMonthSumVO> getEndDateForListEndVO(
			List<LogicWarehouseEndMonthSumVO> endMonth,
			Map<String, LogicWarehouseEndMonthSumVO> endMonthMap,
			Map<String, BasicMaterialsDO> materials,
			Map<String, BasicMaterialsTypeDO> materialsType,
			Map<String, BasicMaterialsTypeDO> materialsSeries
			) throws Exception {
		for(LogicWarehouseEndMonthSumVO vo:endMonthMap.values()){
			vo.setZdTaskQuantity(((vo.getZdTaskQuantity()==null||vo.getZdTaskQuantity().compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:vo.getZdTaskQuantity()));
			vo.setZdTaskSumMoney(((vo.getZdTaskSumMoney()==null||vo.getZdTaskSumMoney().compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:vo.getZdTaskSumMoney()));
			vo.setZdInQuantity(((vo.getZdInQuantity()==null||vo.getZdInQuantity().compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:vo.getZdInQuantity()));
			vo.setZdInSumMoney(((vo.getZdInSumMoney()==null||vo.getZdInSumMoney().compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:vo.getZdInSumMoney()));
			BigDecimal allMoney=vo.getZdTaskSumMoney().add(vo.getZdInSumMoney());
			BigDecimal allQuantity=vo.getZdTaskQuantity().add(vo.getZdInQuantity());
			BigDecimal zdAvgPrice=allMoney.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:(allMoney.divide(allQuantity,4));
			vo.setZdAvgPrice(zdAvgPrice);
			vo.setZdOutQuantity(((vo.getZdOutQuantity()==null||vo.getZdOutQuantity().compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:vo.getZdOutQuantity()));
			BigDecimal outq=vo.getZdOutQuantity().multiply(zdAvgPrice).setScale(4,BigDecimal.ROUND_HALF_UP);
			vo.setZdOutSumMoney((outq==null||outq.compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:outq);
			vo.setZdStockQuantity(((vo.getZdStockQuantity()==null||vo.getZdStockQuantity().compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:vo.getZdStockQuantity()));
			BigDecimal sMoney=vo.getZdStockQuantity().multiply(zdAvgPrice).setScale(4,BigDecimal.ROUND_HALF_UP);
			vo.setZdStockSumMoney((sMoney==null||sMoney.compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:sMoney);
			if(vo.getZdInQuantity().compareTo(BigDecimal.ZERO)==0){
				if(vo.getZdOutQuantity().compareTo(BigDecimal.ZERO)==0){
					if(vo.getZdTaskQuantity().compareTo(BigDecimal.ZERO)==0){
						if(vo.getZdStockQuantity().compareTo(BigDecimal.ZERO)==0){
							continue;
						}
					}
				}
			}
			BasicMaterialsDO mat=materials.get(vo.getZdMaterCode());
			if(mat==null){
				continue;
			}else{
				if(vo.getZdMaterUnit()==null||StringUtils.isBlank(vo.getZdMaterUnit())){
					vo.setZdMaterUnit(mat.getBasicStapleUnitDO()==null?null:mat.getBasicStapleUnitDO().getZd002Name());
				}
			}
			//系列
			BasicMaterialsTypeDO series=materialsSeries.get(mat.getZd001Code());
			if(series==null){
			}else{
				vo.setZdMaterSery(series.getZd002Name());
			}
			BasicMaterialsTypeDO materialType=materialsType.get(mat.getZd029MaterTypeId());
			if(materialType==null){
			}else {
				vo.setZdMaterTypeName(materialType.getZd002Name());
			}
			endMonth.add(vo);
		}
		return endMonth;
	}

	/**
	 * 获取当前选择时间的 仓库的盘点单据以及上次的当局 key 为仓库编码
	 * @param request
	 * @return
	 */
	private Map<String , Map<String, LogicWhCheckTaskDO>> getCtWhMap(HttpServletRequest request)
		throws Exception{
		Map<String , Map<String, LogicWhCheckTaskDO>> ctwhMap= new HashMap<String, Map<String, LogicWhCheckTaskDO>>();
		String whCode = request.getParameter("whCode");
		String dateStr=request.getParameter("date");//系统导出传过来的是是年月 201506
		if(StringUtils.isBlank(whCode)||StringUtils.isBlank(dateStr)){
			return ctwhMap;
		}
		SearchConditions scs= new SearchConditions();
		scs.setLimitClause(null);
		scs.setLimitPage(false);
		SimpleDateFormat sdf= new SimpleDateFormat("yyyyMM");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");
		Date sDate=new SimpleDateFormat("yyyyMMdd").parse(dateStr.trim()+"01");//转变为年月日
		Date dateEnd=org.apache.commons.lang.time.DateUtils.addMonths(sDate, 1);//下一个月做上个月的盘点
		dateEnd=DateUtils.getMonthEnd(dateEnd);//获取这个月的最后一天
		String ds=new SimpleDateFormat("yyyyMMdd").format(dateEnd);
		dateEnd=sdf1.parse(ds.trim()+"235959");
		scs.addCondition("zd009BillType", BillStatusUtil.MONTHCHECK,SearchCondition.OP_EQUAL);
		scs.addCondition("zd003TaskStatus", BillStatusUtil.WH_CHECK_TASK_FOUR,SearchCondition.OP_EQUAL);//完结
		scs.addCondition("zd008StepDate",dateEnd,SearchCondition.OP_SMALLER);//小于
		scs.addCondition("zd001WhCode", whCode, SearchCondition.OP_EQUAL);//完结
		scs.setOrderBy("zd008StepDate desc");
		List<LogicWhCheckTaskDO> ctList= this.logicWhCheckTaskDAO.find(scs);
		Integer findDate= Integer.valueOf(sdf.format(dateEnd));//201507
		for(int i=0 ; i<ctList.size() ; i++){//list 为排序list
			LogicWhCheckTaskDO ct=ctList.get(i);
			Map<String, LogicWhCheckTaskDO> ctMap=ctwhMap.get(ct.getZd001WhCode());
			Integer stepDate=Integer.valueOf(sdf.format(ct.getZd008StepDate()));//审核日期 年月
			if(ctMap==null||ctMap.isEmpty()||ctMap.size()==0){//第一次进入
				if(stepDate.equals(findDate)){ //审核日期 小于于等于本次的 选择时间 201507
					ctMap= new HashMap<String, LogicWhCheckTaskDO>();
					ctMap.put("end", ct);
				}else{
					continue;
				}
			}else{
				LogicWhCheckTaskDO endCt=ctMap.get("end");
				if(endCt==null){
					continue;
				}else{
					LogicWhCheckTaskDO startCt=ctMap.get("start");
					if(startCt==null){//最近的一笔
						ctMap.put("start", ct);
					}
				}
			}
			ctwhMap.put(ct.getZd001WhCode(), ctMap);
		}
		return ctwhMap;
	}

	/**
	 * 获取期末数据
	 * @param request
	 * @param endMonthMap
	 * @param storageMap
	 * @return
	 */
	private Map<String, LogicWarehouseEndMonthSumVO> getEndDate(HttpServletRequest request,
				Map<String, LogicWarehouseEndMonthSumVO> endMonthMap,Map<String , BasicStorageInfoTestDO> storageMap,
				Map<String , BasicStorageInfoTypeTestDO> tMap, String whCode, String dateStr) {
		//SearchConditions scs=this.findNewConditions(request, "logic_warehouse_history", "zd011Date", "zd001WhCode");//月末数据
		SearchConditions scs = new SearchConditions();
		scs.addCondition("zd001WhCode", whCode, SearchCondition.OP_EQUAL); //key 是whcode 仓库编码
		scs.addCondition("zd011Date", dateStr, BillStatusUtil.OP_INMONTH);
		scs.setRemovedProperty(null);
		List<LogicWarehouseHistoryDO> lhList=this.logicWarehouseHistoryDAO.findListByCondition(scs);
		for(LogicWarehouseHistoryDO hs:lhList){
			if(hs==null||hs.getZd009Quantity()==null||hs.getZd009Quantity().compareTo(BigDecimal.ZERO)<=0){
				continue;
			}
			//code name model spec color quanlity storageCode
			String key=(StringUtils.isEmpty(hs.getZd002MaterialCode())?null:hs.getZd002MaterialCode())+"_"+
							(StringUtils.isEmpty(hs.getZd002MaterialName())?null:hs.getZd002MaterialName())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialModel())?null:hs.getZd003MaterialModel())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialSpec())?null:hs.getZd003MaterialSpec())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialColor())?null:hs.getZd003MaterialColor())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialQuanlity())?null:hs.getZd003MaterialQuanlity())+"_"+
							(StringUtils.isEmpty(hs.getZd001WhCode())?null:hs.getZd001WhCode());
			BasicStorageInfoTestDO storage=storageMap.get(hs.getZd001WhCode());
			if(storage==null){
				throw new SyBaseException("此仓库不存在!!!!");
			}
			BasicStorageInfoTypeTestDO storageType=tMap.get(storage.getZd001WhTypeId());
			if(storageType!=null&&storageType.getZd001Code().equals("WHLX1411170001")){//成品仓库
				key=key+"_"+(StringUtils.isEmpty(hs.getZd006PiCode())?null:hs.getZd006PiCode());
			}
			if("c0450".equals(hs.getZd002MaterialCode())){
				System.out.println("materical code ======"+hs.getZd002MaterialCode());
			}
			LogicWarehouseEndMonthSumVO vo=endMonthMap.get(key);
			if(vo==null){
				vo=new LogicWarehouseEndMonthSumVO();
			}
			vo.setPiCode(hs.getZd006PiCode());
			vo.setZdMaterCode(hs.getZd002MaterialCode());
			vo.setZdMaterColor(hs.getZd003MaterialColor());
			vo.setZdMaterModel(hs.getZd003MaterialModel());
			vo.setZdMaterName(hs.getZd002MaterialName());
			vo.setZdMaterQuanlity(hs.getZd003MaterialQuanlity());
			vo.setZdMaterSize(hs.getZd003MaterialSpec());
			//vo.setZdMaterUnit(hs.getZd010Unit());
			vo.setZdWhName(hs.getZd001WhName());
			vo.setZdWhCode(hs.getZd001WhCode());
			vo.setZdCompNameEnd(hs.getZd008CustomerName());
			//总数量
//			vo.setZdStockQuantity((vo.getZdStockQuantity()==null?BigDecimal.ZERO:vo.getZdStockQuantity()).
//					add(hs.getZd009Quantity()==null?BigDecimal.ZERO:hs.getZd009Quantity()));
			vo.setZdStockQuantity( hs.getZd009Quantity()==null?BigDecimal.ZERO:hs.getZd009Quantity());
			endMonthMap.put(key, vo);
		}
		return endMonthMap;
	}

	/**
	 * 获取期末数据
	 * @param request
	 * @param endMonthMap
	 * @param storageMap
	 * @return
	 */
	private Map<String, LogicWarehouseEndMonthSumVO> getEndDate(HttpServletRequest request,
				Map<String, LogicWarehouseEndMonthSumVO> endMonthMap,
					Map<String , BasicStorageInfoTestDO> storageMap,
						Map<String , BasicStorageInfoTypeTestDO> tMap,
						Map<String , Map<String, LogicWhCheckTaskDO>> ctwhMap) {
		for(String keyStr:ctwhMap.keySet()){
			SearchConditions scs=this.findNewConditions(request, "logic_warehouse_history", "zd011Date", "zd001WhCode");//月末数据
			scs.addCondition("zd001WhCode", keyStr); //key 是whcode 仓库编码
			scs.setRemovedProperty(null);
			List<LogicWarehouseHistoryDO> lhList=this.logicWarehouseHistoryDAO.findListByCondition(scs);
			for(LogicWarehouseHistoryDO hs:lhList){
				if(hs==null||hs.getZd009Quantity()==null||hs.getZd009Quantity().compareTo(BigDecimal.ZERO)<=0){
					continue;
				}
				//code name model spec color quanlity storageCode
				String key=(StringUtils.isEmpty(hs.getZd002MaterialCode())?null:hs.getZd002MaterialCode())+"_"+
								(StringUtils.isEmpty(hs.getZd002MaterialName())?null:hs.getZd002MaterialName())+"_"+
								(StringUtils.isEmpty(hs.getZd003MaterialModel())?null:hs.getZd003MaterialModel())+"_"+
								(StringUtils.isEmpty(hs.getZd003MaterialSpec())?null:hs.getZd003MaterialSpec())+"_"+
								(StringUtils.isEmpty(hs.getZd003MaterialColor())?null:hs.getZd003MaterialColor())+"_"+
								(StringUtils.isEmpty(hs.getZd003MaterialQuanlity())?null:hs.getZd003MaterialQuanlity())+"_"+
								(StringUtils.isEmpty(hs.getZd001WhCode())?null:hs.getZd001WhCode());
				BasicStorageInfoTestDO storage=storageMap.get(hs.getZd001WhCode());
				if(storage==null){
					throw new SyBaseException("此仓库不存在!!!!");
				}
				BasicStorageInfoTypeTestDO storageType=tMap.get(storage.getZd001WhTypeId());
				if(storageType!=null&&storageType.getZd001Code().equals("WHLX1411170001")){//成品仓库
					key=key+"_"+(StringUtils.isEmpty(hs.getZd006PiCode())?null:hs.getZd006PiCode());
				}
				LogicWarehouseEndMonthSumVO vo=endMonthMap.get(key);
				if(vo==null){
					vo=new LogicWarehouseEndMonthSumVO();
				}
				vo.setPiCode(hs.getZd006PiCode());
				vo.setZdMaterCode(hs.getZd002MaterialCode());
				vo.setZdMaterColor(hs.getZd003MaterialColor());
				vo.setZdMaterModel(hs.getZd003MaterialModel());
				vo.setZdMaterName(hs.getZd002MaterialName());
				vo.setZdMaterQuanlity(hs.getZd003MaterialQuanlity());
				vo.setZdMaterSize(hs.getZd003MaterialSpec());
				//vo.setZdMaterUnit(hs.getZd010Unit());
				vo.setZdWhName(hs.getZd001WhName());
				vo.setZdWhCode(hs.getZd001WhCode());
				vo.setZdCompNameEnd(hs.getZd008CustomerName());
				//总数量
				vo.setZdStockQuantity((vo.getZdStockQuantity()==null?BigDecimal.ZERO:vo.getZdStockQuantity()).
						add(hs.getZd009Quantity()==null?BigDecimal.ZERO:hs.getZd009Quantity()));
				endMonthMap.put(key, vo);
			}

		}
		return endMonthMap;
	}
	/**
	 * huoqu
	 * @param request
	 * @param endMonthMap
	 * @param storageMap
	 * @return
	 */
	private Map<String , LogicWarehouseEndMonthSumVO> getMiddleData(HttpServletRequest request,
				Map<String, LogicWarehouseEndMonthSumVO> endMonthMap,
					Map<String , BasicStorageInfoTestDO> storageMap,
						Map<String , BasicStorageInfoTypeTestDO> tMap,
						Map<String , Map<String, LogicWhCheckTaskDO>> ctwhMap) throws SyBaseException{
		try {
			String msg="出入库记录查询开始时间:"+new SimpleDateFormat("hh:mm:dd").format(new Date());
			for(String keyStr:ctwhMap.keySet()){
				if(StringUtils.isBlank(keyStr)){
					continue;
				}
				 Map<String, LogicWhCheckTaskDO> ctMap= ctwhMap.get(keyStr);
				 LogicWhCheckTaskDO cts=ctMap.get("start");
				 LogicWhCheckTaskDO cte=ctMap.get("end");
				 Map<String, Object> paramMap=new HashMap<String, Object>();
				 if(cts!=null){
					 paramMap.put("beforeDate", cts.getBizModifyDate());
				 }
				 if(cte!=null){
					 paramMap.put("endDate", cte.getBizModifyDate());
				 }
				 paramMap.put("whcode", keyStr);
				 List<MiddleDataVO> listMD=this.excelExportDAO.findMDVBy(paramMap);
				 for(MiddleDataVO mvo:listMD){
					 if("00005".equals(mvo.getMcode())){
						System.out.println();
					 }
					 if("00155".equals(mvo.getMcode())){
							System.out.println();
						 }
						//code name model spec color quanlity storageCode
						String key=(StringUtils.isEmpty(mvo.getMcode())?null:mvo.getMcode()) +"_"+
								(StringUtils.isEmpty(mvo.getMname())?null:mvo.getMname()) +"_"+
								(StringUtils.isEmpty(mvo.getMmodel())?null:mvo.getMmodel()) +"_"+
								(StringUtils.isEmpty(mvo.getMspec())?null:mvo.getMspec()) +"_"+
								(StringUtils.isEmpty(mvo.getMcolor())?null:mvo.getMcolor()) +"_"+
								(StringUtils.isEmpty(mvo.getMquanlity())?null:mvo.getMquanlity())+"_"+
								(StringUtils.isEmpty(mvo.getWhcode())?null:mvo.getWhcode());
						BasicStorageInfoTestDO storage=storageMap.get(mvo.getWhcode());
						if(storage==null){
							throw new SyBaseException("此仓库不存在!!!!");
						}
						BasicStorageInfoTypeTestDO storageType=tMap.get(storage.getZd001WhTypeId());
						if(storageType!=null&&storageType.getZd001Code().equals("WHLX1411170001")){//成品仓库
							key=key+"_"+(StringUtils.isEmpty(mvo.getMpicode())?null:mvo.getMpicode());
						}
						LogicWarehouseEndMonthSumVO vo=endMonthMap.get(key);
						if(vo==null){
							vo= new LogicWarehouseEndMonthSumVO();
						}
						if(mvo.getMiquantity().compareTo(BigDecimal.ZERO)!=0){//入库
							//入库总金额=以前+现在总金额
							vo.setZdInSumMoney((vo.getZdInSumMoney()==null?BigDecimal.ZERO:vo.getZdInSumMoney()).
									add((mvo.getMiquantity()==null?BigDecimal.ZERO:mvo.getMiquantity())
											.multiply((mvo.getMprice()==null?BigDecimal.ZERO:mvo.getMprice()))));
							//入库数
							vo.setZdInQuantity((vo.getZdInQuantity()==null?BigDecimal.ZERO:vo.getZdInQuantity()).
									add(mvo.getMiquantity()==null?BigDecimal.ZERO:mvo.getMiquantity()));
							vo.setZdCompNameIn(mvo.getMcname());
						}
						if(mvo.getMoquantity().compareTo(BigDecimal.ZERO)!=0){//出库
							vo.setZdOutQuantity((vo.getZdOutQuantity()==null?BigDecimal.ZERO:vo.getZdOutQuantity()).
									add(mvo.getMoquantity()==null?BigDecimal.ZERO:mvo.getMoquantity()));
							vo.setZdCompNameOut(mvo.getMcname());
						}
						vo.setZdMaterCode(mvo.getMcode());
						vo.setZdMaterName(mvo.getMname());
						vo.setZdMaterModel(mvo.getMmodel());
						vo.setZdMaterSize(mvo.getMspec());
						vo.setZdMaterQuanlity(mvo.getMquanlity());
						vo.setZdMaterColor(mvo.getMcolor());
						vo.setZdWhCode(mvo.getWhcode());
						vo.setZdWhName(mvo.getWhname());
						vo.setZdCompCode(mvo.getMcode());//客户 or 供应商
						vo.setZdMaterUnit(mvo.getMunit());
						vo.setPiCode(mvo.getMpicode());
						endMonthMap.put(key, vo);
					}
			}
			msg=msg+",出入库记录查询结束时间:"+new SimpleDateFormat("hh:mm:dd").format(new Date())	;
			System.out.println(msg);
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(e);
		}
		return endMonthMap;
	}

	/**
	 * 获取期初数据
	 * @param request
	 * @param endMonthMap
	 * @param storageMap
	 * @return
	 * @throws SyBaseException
	 */
	private Map<String, LogicWarehouseEndMonthSumVO> getBeforDate(HttpServletRequest request,
				Map<String, LogicWarehouseEndMonthSumVO> endMonthMap,
					Map<String , BasicStorageInfoTestDO> storageMap,
					Map<String , BasicStorageInfoTypeTestDO> tMap,
					LogicWhCheckTaskDO qcCheckTask) throws SyBaseException{
		try {
			//不存在期初
			if(qcCheckTask==null||StringUtils.isBlank(qcCheckTask.getId())){
				return endMonthMap;
			}
			//当前仓库有期初数据
			SearchConditions scs= new SearchConditions();
			scs.setLimitClause(null);
			scs.setLimitPage(false);
			scs.addCondition("logic_wh_check_task_item.zd001TaskId", qcCheckTask.getId());
			List<InOutBillDO> ctList=logicWhCheckTaskItemDAO.findCheckTaskList(scs);
			for(InOutBillDO ct:ctList){
				//code name model spec color quanlity storageCode
				String key=(StringUtils.isEmpty(ct.getMaterialCode())?null:ct.getMaterialCode()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialName())?null:ct.getMaterialName()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialModel())?null:ct.getMaterialModel()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialSpec())?null:ct.getMaterialSpec()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialColor())?null:ct.getMaterialColor()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialQuanlity())?null:ct.getMaterialQuanlity()) +"_"+
						(StringUtils.isEmpty(ct.getStorageCode())?null:ct.getStorageCode());
				BasicStorageInfoTestDO storage=storageMap.get(ct.getStorageCode());
				if(storage==null){
					throw new SyBaseException("此仓库不存在!!!!");
				}
				//comsumerId
				BasicStorageInfoTypeTestDO storageType=tMap.get(storage.getZd001WhTypeId());
				if(storageType!=null&&storageType.getZd001Code().equals("WHLX1411170001")){//成品仓库
					key=key+"_"+(StringUtils.isEmpty(ct.getPiCode())?null:ct.getPiCode());
				}
				LogicWarehouseEndMonthSumVO vo= endMonthMap.get(key);
				if(vo==null){
					vo= new LogicWarehouseEndMonthSumVO();
				}
				vo.setZdTaskQuantity((vo.getZdTaskQuantity()==null?BigDecimal.ZERO:vo.getZdTaskQuantity()).
						add(ct.getInQuantity()==null?BigDecimal.ZERO:ct.getInQuantity()));
				vo.setZdTaskSumMoney((vo.getZdTaskSumMoney()==null?BigDecimal.ZERO:vo.getZdTaskSumMoney()).
						add((ct.getInQuantity()==null?BigDecimal.ZERO:ct.getInQuantity()).
						multiply((ct.getMaterialPrice()==null?BigDecimal.ZERO:ct.getMaterialPrice()))));
				vo.setZdMaterCode(ct.getMaterialCode());
				vo.setZdMaterName(ct.getMaterialName());
				vo.setZdMaterModel(ct.getMaterialModel());
				vo.setZdMaterSize(ct.getMaterialSpec());
				vo.setZdMaterQuanlity(ct.getMaterialQuanlity());
				vo.setZdMaterColor(ct.getMaterialColor());
				vo.setZdWhCode(ct.getStorageCode());
				vo.setZdWhName(ct.getStorageName());
				vo.setZdWhId(ct.getStorageId());
				vo.setZdCompName(ct.getConsumerName());//客户 or 供应商
				vo.setZdMaterUnit(ct.getMaterialUnit());
				vo.setPiCode(ct.getPiCode());
				endMonthMap.put(key, vo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(e);
		}
		return endMonthMap;
	}

	/**
	 * 获取期初数据
	 * @param request
	 * @param endMonthMap
	 * @param storageMap
	 * @return
	 * @throws SyBaseException
	 */
	private Map<String, LogicWarehouseEndMonthSumVO> getBeforDate(HttpServletRequest request,
				Map<String, LogicWarehouseEndMonthSumVO> endMonthMap,
					Map<String , BasicStorageInfoTestDO> storageMap,
					Map<String , BasicStorageInfoTypeTestDO> tMap,
					Map<String , Map<String, LogicWhCheckTaskDO>> ctwhMap) throws SyBaseException{
		try {
			for(String keyStr:ctwhMap.keySet()){
				Map<String, LogicWhCheckTaskDO> ctMap=ctwhMap.get(keyStr);
				LogicWhCheckTaskDO ctd=ctMap.get("start");
				if(ctd!=null){//当前仓库有期初数据
					SearchConditions scs= new SearchConditions();
					scs.setLimitClause(null);
					scs.setLimitPage(false);
					scs.addCondition("logic_wh_check_task_item.zd001TaskId", ctd.getId());
					List<InOutBillDO> ctList=logicWhCheckTaskItemDAO.findCheckTaskList(scs);
					for(InOutBillDO ct:ctList){
						//code name model spec color quanlity storageCode
						String key=(StringUtils.isEmpty(ct.getMaterialCode())?null:ct.getMaterialCode()) +"_"+
								(StringUtils.isEmpty(ct.getMaterialName())?null:ct.getMaterialName()) +"_"+
								(StringUtils.isEmpty(ct.getMaterialModel())?null:ct.getMaterialModel()) +"_"+
								(StringUtils.isEmpty(ct.getMaterialSpec())?null:ct.getMaterialSpec()) +"_"+
								(StringUtils.isEmpty(ct.getMaterialColor())?null:ct.getMaterialColor()) +"_"+
								(StringUtils.isEmpty(ct.getMaterialQuanlity())?null:ct.getMaterialQuanlity()) +"_"+
								(StringUtils.isEmpty(ct.getStorageCode())?null:ct.getStorageCode());
						BasicStorageInfoTestDO storage=storageMap.get(ct.getStorageCode());
						if(storage==null){
							throw new SyBaseException("此仓库不存在!!!!");
						}
						//comsumerId
						BasicStorageInfoTypeTestDO storageType=tMap.get(storage.getZd001WhTypeId());
						if(storageType!=null&&storageType.getZd001Code().equals("WHLX1411170001")){//成品仓库
							key=key+"_"+(StringUtils.isEmpty(ct.getPiCode())?null:ct.getPiCode());
						}
						LogicWarehouseEndMonthSumVO vo= endMonthMap.get(key);
						if(vo==null){
							vo= new LogicWarehouseEndMonthSumVO();
						}
						vo.setZdTaskQuantity((vo.getZdTaskQuantity()==null?BigDecimal.ZERO:vo.getZdTaskQuantity()).
								add(ct.getInQuantity()==null?BigDecimal.ZERO:ct.getInQuantity()));
						vo.setZdTaskSumMoney((vo.getZdTaskSumMoney()==null?BigDecimal.ZERO:vo.getZdTaskSumMoney()).
								add((ct.getInQuantity()==null?BigDecimal.ZERO:ct.getInQuantity()).
								multiply((ct.getMaterialPrice()==null?BigDecimal.ZERO:ct.getMaterialPrice()))));
						vo.setZdMaterCode(ct.getMaterialCode());
						vo.setZdMaterName(ct.getMaterialName());
						vo.setZdMaterModel(ct.getMaterialModel());
						vo.setZdMaterSize(ct.getMaterialSpec());
						vo.setZdMaterQuanlity(ct.getMaterialQuanlity());
						vo.setZdMaterColor(ct.getMaterialColor());
						vo.setZdWhCode(ct.getStorageCode());
						vo.setZdWhName(ct.getStorageName());
						vo.setZdWhId(ct.getStorageId());
						vo.setZdCompName(ct.getConsumerName());//客户 or 供应商
						vo.setZdMaterUnit(ct.getMaterialUnit());
						vo.setPiCode(ct.getPiCode());
						endMonthMap.put(key, vo);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(e);
		}
		return endMonthMap;
	}
	/**
	 * 获取仓库
	 * @param request
	 * @param tableName 表名（查询的别名）
	 * @param field 时间字段名
	 * @param whCode 仓库名称
	 * @return
	 * @throws SyBaseException
	 */
	@SuppressWarnings("unchecked")
	private SearchConditions findNewConditions(HttpServletRequest request,String tableName,String field,
			String whCode)throws SyBaseException{
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs= new SearchConditions();
		hander.getWheres(scs);
		try {
			hander.setFilters(new String(request.getParameter("filters").getBytes(
					"ISO-8859-1"), "UTF-8"));
			scs.clearCondition();
			hander.getWheres(scs);
			Collection<SearchCondition> condition=scs.getConditions();
			for(SearchCondition sc:condition){
				if("date".equals(sc.getField())){
					sc.setOperator(BillStatusUtil.OP_INMONTH);
					sc.setValue((sc.getValue()+"").trim());
				}
				sc.setField(tableName+"."+field);
			}
			Map<String,Object> sqlWHMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,tableName+"."+whCode);
			scs.addCondition(sqlWHMap.get("option")+"",(List<String>)sqlWHMap.get("roleWhList"));
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(e);
		}
		scs.setLimitClause(null);
		scs.setLimitPage(false);
		return scs;
	}




	@Override
	public List<InOutBillDO> findBatchInExce(HttpServletRequest request)
			throws SyBaseException {
		SearchConditions scs=this.getCondition(request, "logic_warehouse_batch_in.zd003WhCode",
				"logic_warehouse_batch_in.zd004InDate","logic_warehouse_batch_in");
		scs.setOrderBy("logic_warehouse_batch_in.zd001Code");
		Collection<SearchCondition> conditions=scs.getConditions();
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_warehouse_batch_in.zd010Stauts")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_warehouse_batch_in.zd010Stauts", BillStatusUtil.BATCH_IN_TWO);
		}
		List<InOutBillDO> batchInList=this.excelExportDAO.findBatchInAndItemByConditions(scs);//多pi入库
		return batchInList;
	}

	public List<UtilsEntityVO> findBOMMaterialAll(HttpServletRequest request){
		//获取现有bom的集合
		SearchConditions scs = new SearchConditions();
		scs.clearCondition();
		scs.setLimitClause(null);
		scs.setRemovedProperty("bpb.removed");
		scs.setLimitPage(false);
		//获取所有bom对应其物料的集合
		List<UtilsEntityVO> bomMaterList = basicProductBomMaterialsDAO.findAllList(scs);
		Map<String, BasicStapleUnitDO> unitMap=oftenMapUtil.getUtilsAllMap();
		List<UtilsEntityVO> needList= new ArrayList<UtilsEntityVO>();
		for(UtilsEntityVO bm:bomMaterList){
			if(unitMap.get(bm.getBomUntl())!=null){
				bm.setBomUntl(unitMap.get(bm.getBomUntl()).getZd002Name());
			}
			needList.add(bm);
		}
		return needList;
	}
	/**
	 * 所有工序
	 * @param request
	 * @return
	 */
	public List<UtilsEntityVO> findBOMProcessListAll(HttpServletRequest request){
		//获取现有bom的集合
		SearchConditions scs = new SearchConditions();
		scs.clearCondition();
		scs.setLimitClause(null);
		scs.setRemovedProperty("bpb.removed");
		scs.setLimitPage(false);
		List<UtilsEntityVO> voList=basicProductBomProcessDAO.findListByCondition(scs);
		//获取所有bom对应其物料的集合
		Map<String, BasicStapleUnitDO> unitMap=oftenMapUtil.getUtilsAllMap();
		List<UtilsEntityVO> needList= new ArrayList<UtilsEntityVO>();
		for(UtilsEntityVO bm:voList){
			if(bm.getBomUntl()==null){
				continue;
			}
			bm.setBomUntl(unitMap.get(bm.getBomUntl())==null?bm.getBomUntl():unitMap.get(bm.getBomUntl()).getZd002Name());
			needList.add(bm);
		}
		return needList;

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LogicSalesDetailVO> findSalesDetailExcel(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= oftenMothedUtil.getNewSearchConditionsPageToJava(request, null);
		scs.setLimitClause(null);
		scs.setLimitPage(false);
		scs.setRemovedProperty("gs.removed");
		scs.setOrderBy("gs.bizCreatorDate desc");
		scs.addCondition("gs.zd024Billstatus",BillStatusUtil.SES_STATUS_ONE,SearchCondition.OP_NOTEQUAL);
		scs=oftenMothedUtil.addSearchConditionsByInMonth(scs, "gs.bizCreatorDate");
		SearchResult sr= logicProductionStorageOutService.findQuerySaleDetailByScs(scs);
		return sr.getResults();
	}

	@Override
	/**
	 * 在没有给定时间区间时默认为本月的数据(其他入库)
	 * @param request
	 * @return
	 * @throws SyBaseException
	 */
	public List<InOutBillDO> findOtherInAndItemByConditions(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= this.getCondition(request,"logic_warehouse_otherin.zd004WhCode",
				"logic_warehouse_otherin.zd010OtherDate","logic_warehouse_otherin");
		scs.setOrderBy("logic_warehouse_otherin.zd001InCode");
		Collection<SearchCondition> conditions=scs.getConditions();
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeKeyMaterialCode(new SearchConditions());
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_warehouse_otherin.zd003BillStatus")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_warehouse_otherin.zd003BillStatus", BillStatusUtil.OTHERWH_BILL_STATUE_FOUR);
		}
		List<InOutBillDO> inOutList=excelExportDAO.findOtherInAndItemByConditions(scs);
		return this.getNewInOutBillDo(materialsType, inOutList,true);
	}

	@Override
	/**
	 *  在没有给定时间区间时默认为本月的数据（其他出库）
	 * @param request
	 * @return
	 * @throws SyBaseException
	 */
	public List<InOutBillDO> findOtherOutAndItemByConditions(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= this.getCondition(request, "logic_warehouse_otherout.zd004WhCode",
				"logic_warehouse_otherout.zd010OtherDate","logic_warehouse_otherout");
		scs.setOrderBy("logic_warehouse_otherout.zd001OutCode");
		Collection<SearchCondition> conditions=scs.getConditions();
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_warehouse_otherout.zd003BillStatus")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_warehouse_otherout.zd003BillStatus",BillStatusUtil.OTHERWH_BILL_STATUE_FOUR);
		}
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeKeyMaterialCode(new SearchConditions());
		List<InOutBillDO> inOutList=excelExportDAO.findOtherOutAndItemByConditions(scs);
		return this.getNewInOutBillDo(materialsType, inOutList,false);
	}

	@Override
	/**
	 * 在没有给定时间区间时默认为本月的数据（采购入库）
	 * @param request
	 * @return
	 * @throws SyBaseException
	 */
	public List<InOutBillDO> findPurchasewareInAndItemByConditions(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= this.getCondition(request, "logic_purchase_ware.zd006WhCode",
				"logic_purchase_ware.zd013Date","logic_purchase_ware");
		scs.setOrderBy("logic_purchase_ware.zd003Code");
		Collection<SearchCondition> conditions=scs.getConditions();
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_purchase_ware.zd004Status")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_purchase_ware.zd004Status", BillStatusUtil.PCSW_BILL_STATUS_FOUR);
		}
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeKeyMaterialCode(new SearchConditions());
		List<InOutBillDO> inOutList=excelExportDAO.findPurchasewareInAndItemByConditions(scs);
		return this.getNewInOutBillDo(materialsType, inOutList,true);
	}
	@Override
	/**
	 * 领料出库
	 */
	public List<InOutBillDO> findMaterialOutAndItemByConditions(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= this.getCondition(request, "logic_warehouse_materialout.zd011WhCode",
				"logic_warehouse_materialout.zd010OtherDate","logic_warehouse_materialout");
		scs.setOrderBy("logic_warehouse_materialout.zd001MaterialCode");
		Collection<SearchCondition> conditions=scs.getConditions();
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_warehouse_materialout.zd003BillStatus")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_warehouse_materialout.zd003BillStatus", BillStatusUtil.MATERIALOUT_BILL_STATUE_FOUR);
		}
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeKeyMaterialCode(new SearchConditions());
		List<InOutBillDO> inOutList=excelExportDAO.findMaterialOutAndItemByConditions(scs);
		return this.getNewInOutBillDo(materialsType, inOutList,false);
	}

	@Override
	/**
	 * 在没有给定时间区间时默认为本月的数据（成品入库）
	 * @param request
	 * @return
	 * @throws SyBaseException
	 */
	public List<InOutBillDO> findSotrageInAndItemByConditions(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= this.getCondition(request, "logic_production_storagein.zd004WhCode" , "logic_production_storagein.zd010OtherDate","logic_production_storagein");
		scs.setOrderBy("logic_production_storagein.zd001InCode");
		Collection<SearchCondition> conditions=scs.getConditions();
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_production_storagein.zd011BillStatus")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_production_storagein.zd011BillStatus", BillStatusUtil.PROSTORIN_STATUS_FIVE);
		}
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeKeyMaterialCode(new SearchConditions());
		List<InOutBillDO> inOutList=excelExportDAO.findSotrageInAndItemByConditions(scs);
		return this.getNewInOutBillDo(materialsType, inOutList,true);
	}

	@Override
	/**
	 * 成品出库导出
	 */
	public List<InOutBillDO> findstorageOutAndItemByConditions(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs=this.getCondition(request, "logic_production_storageout.zd004WhCode",
				"logic_production_storageout.zd010OtherDate","logic_production_storageout");
		scs.setOrderBy("logic_production_storageout.zd001OutCode");
		Collection<SearchCondition> conditions=scs.getConditions();
		boolean isOk=true;
		for(SearchCondition sc:conditions){
			if(sc.getField().equals("logic_production_storageout.zd011BillStatus")){
				isOk=false;
			}
		}
		if(isOk){
			scs.addCondition("logic_production_storageout.zd011BillStatus", BillStatusUtil.PROSTOROUT_STATUS_FIVE);
		}
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeKeyMaterialCode(new SearchConditions());
		List<InOutBillDO> inOutList=excelExportDAO.findstorageOutAndItemByConditions(scs);
		return this.getNewInOutBillDo(materialsType, inOutList,false);
	}
	/**
	 * @param request
	 * @param whCode 仓库字段名称
	 * @param field 确认建单的时间
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private  SearchConditions getCondition(HttpServletRequest request, String whCode , String field,String tableName) {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs= new SearchConditions();
		hander.getWheres(scs);
		try {
			hander.setFilters(new String(request.getParameter("filters").getBytes(
					"ISO-8859-1"), "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		scs.clearCondition();
		hander.getWheres(scs);
		Collection<SearchCondition> condition=scs.getConditions();
		boolean isok=true;
		for(SearchCondition sc:condition){
			if(StringUtils.isNotBlank(sc.getField())){
				String[] fieldArr=sc.getField().split(".");
				if(fieldArr.length>0){
					sc.setField(tableName+"."+fieldArr[fieldArr.length-1]);
				}else{
					sc.setField(tableName+"."+sc.getField());
				}

			}
			if(sc.getOperator().equals(SearchCondition.OP_GREATER)||sc.getOperator().equals(SearchCondition.OP_SMALLER)){
				isok=false;
			}
		}
		if(isok){
			scs.addCondition(new SearchCondition(field, BillStatusUtil.OP_INMONTH, new SimpleDateFormat("yyyyMM").format(new Date())));
		}
		Map<String,Object> sqlWHMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,whCode);
		scs.addCondition(sqlWHMap.get("option")+"",(List<String>)sqlWHMap.get("roleWhList"));
		return scs;
	}

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 在没有给定时间区间时默认为本月的数据
	 * @param request
	 * @return
	 * @throws SyBaseException
	 */
	public List<LogicProductionDispatchingDetailItemVO> findDispatchingDetatlsReports(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs=new SearchConditions();
		scs= oftenMothedUtil.getNewSearchConditionsPageToJava(request, null);
		scs= oftenMothedUtil.addSearchConditionsByInMonth(scs, "logic_production_dispatching_detail.zd008WorkDate");
		scs.setLimitClause(null);
		scs.setRemovedProperty(null);;
		scs.setOrderBy("logic_production_dispatching_detail.zd001FormCode");
		scs.addCondition("logic_production_dispatching_detail.zd008WorkStatus", BillStatusUtil.PRODISPATDTL_BILL_STATUS_ZONE);
		SearchResult sr= logicProductionDispatchingService.findDispatchingDetailBySCS(scs);
		List<LogicProductionDispatchingDetailItemVO>  list=sr.getResults();
		List<LogicProductionDispatchingDetailItemVO>  listNeW=new ArrayList<LogicProductionDispatchingDetailItemVO>();
		for(LogicProductionDispatchingDetailItemVO vo:list){
			if(vo==null){
				continue;
			}
			vo.setAllprice(vo.getAllprice().setScale(2,BigDecimal.ROUND_HALF_UP));
			if(vo.getAllprice().compareTo(BigDecimal.ZERO)==0){
				continue;
			}
			vo.setZd014Price(vo.getZd014Price().setScale(2,BigDecimal.ROUND_HALF_UP));

			vo.setZdTheQuantity(vo.getZdTheQuantity().setScale(2,BigDecimal.ROUND_HALF_UP));
			listNeW.add(vo);
		}
		return listNeW;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LogicWarehouseEndMonthSumVO> findWarehouseEndMOthSumList(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= new SearchConditions();
		scs=oftenMothedUtil.getNewSearchConditionsPageToJava(request, null);
		//scs=oftenMothedUtil.addSearchConditionsByInMonth(scs, null);
		return  logicReportsUtilService.findQueryEndMonthToSummary(scs).getResults();
	}
	@Override
	public List<LogicSalesDetailVO> finSalesDerailList(
			HttpServletRequest request) throws SyBaseException {
		SearchConditions scs= new SearchConditions();
		scs=oftenMothedUtil.getNewSearchConditionsPageToJava(request, null);
		scs=oftenMothedUtil.addSearchConditionsByInMonth(scs, null);
		return null;
	}
	private List<InOutBillDO> getNewInOutBillDo(
			Map<String, BasicMaterialsTypeDO> materialsType,
			List<InOutBillDO> inOutList,boolean isin) {
		List<InOutBillDO> iOList= new ArrayList<InOutBillDO>();
		for(InOutBillDO io:inOutList){
			if(StringUtils.isNotBlank(io.getConsumerName())){
				String[] arr=io.getConsumerName().split("-");
				io.setSalesman(arr[arr.length-1]);
			}
			BasicMaterialsTypeDO bt=materialsType.get(io.getMaterialCode());
			if(bt!=null){
				io.setMaterialType(bt.getZd002Name());
			}
			if(isin){
				if(StringUtils.isNotBlank(io.getConsumerName())){
					String[] arr=io.getConsumerName().split("-");
					io.setSalesman(arr[arr.length-1]);
				}
				if(io.getInQuantity().compareTo(BigDecimal.ZERO)==1){
					iOList.add(io);
				}
			}else{
				if(StringUtils.isNotBlank(io.getOutConsumerName())){
					String[] arr=io.getOutConsumerName().split("-");
					io.setConsumerName(io.getOutConsumerName());
					io.setSalesman(arr[arr.length-1]);
				}
				if(io.getOutQuantity().compareTo(BigDecimal.ZERO)==1){
					iOList.add(io);
				}
			}
		}
		return iOList;
	}

	@SuppressWarnings({ "unchecked", "unused" })
	@Override
	@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
	public List<LogicWarehouseEndMonthSumVO> finEndMonthExcel(HttpServletRequest request)
			throws SyBaseException {
		List<LogicWarehouseEndMonthSumVO> endMonth=new ArrayList<LogicWarehouseEndMonthSumVO>();
		Map<String, LogicWarehouseEndMonthSumVO> endMonthMap= new HashMap<String, LogicWarehouseEndMonthSumVO>();
		Map<String, LogicWarehouseEndMonthSumVO> monthMap= new HashMap<String, LogicWarehouseEndMonthSumVO>();
		SearchConditions scs= this.getConditionByEndMonth(request, "zd012WareHouseCode", "bizCreatorDate", "logic_excel_to_store", "excel");
		List<LogicExcelToStoreDO> excelList=this.logicExcelToStoreService.findListByExample(scs).getResults();//查询所有的期初
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions sc= new SearchConditions();
		hander.getWheres(sc);
		try {
			hander.setFilters(new String(request.getParameter("filters").getBytes(
					"ISO-8859-1"), "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		sc.clearCondition();
		hander.getWheres(sc);
		Collection<SearchCondition> condition=sc.getConditions();
		boolean isOk = false;
		boolean isBegin= false;
		String sdate="";
		for(SearchCondition s:condition){
			if("date".equals(s.getField())){
				sdate=s.getValue()+"";
				isOk=true;
				try {
					Integer min=Integer.valueOf((s.getValue()+"").trim());
					if(min<201412){
						isOk=false;
					}
				} catch (Exception e) {
					return new ArrayList<LogicWarehouseEndMonthSumVO>();
				}
				if("201412".equals((s.getValue()+"").trim())){//第一次获取月末汇总表
					isBegin=true;
				}
			}
		}
		if(!isOk){
			return new ArrayList<LogicWarehouseEndMonthSumVO>();
		}
		if(isBegin){//期初
			endMonthMap =this.getExcelMap(excelList,true);
		}else{
			endMonthMap=getEndMonthMap(request, scs, excelList);
		}
		//获得调拨的数据
		scs.clearCondition();
		//scs=this.getConditionByEndMonth(request, "zd003OutWhCode", "zd005OutDate", "logic_allocation","db");
//		scs=this.getConditionByEndMonth(request, "zd003OutWhCode", "bizModifyDate", "logic_allocation","db");
		scs.addCondition("logic_allocation.zd005OutDate", sdate,BillStatusUtil.OP_INMONTH);
		scs.addCondition("logic_allocation.zd002Status", BillStatusUtil.ACT_BILL_STATUS_ZTWO);
		scs.setLimitClause(null); scs.setLimitPage(false);
		List<InOutBillDO> inList=this.excelExportDAO.findAllocationtAndItemByConditions(scs);
		List<InOutBillDO> outList=this.excelExportDAO.findAllocationtAndItemByConditions(scs);
		List<InOutBillDO> allOctionOutList= new ArrayList<InOutBillDO>();
		List<InOutBillDO> allOctionInList= new ArrayList<InOutBillDO>();
		// inStorage
		for(InOutBillDO io:inList){
			io.setStorageName(io.getInStorageName());
			io.setStorageCode(io.getInStorageCode());
			io.setOutQuantity(BigDecimal.ZERO);
			io.setInStorageCode(null);
			io.setInStorageName(null);
			io.setOutStorageCode(null);
			io.setOutStorageName(null);
			allOctionInList.add(io);
		}
		//outStorage
		for(InOutBillDO io:outList){
			io.setStorageName(io.getOutStorageName());
			io.setStorageCode(io.getOutStorageCode());
			io.setInQuantity(BigDecimal.ZERO);
			io.setInStorageCode(null);
			io.setInStorageName(null);
			io.setOutStorageCode(null);
			io.setOutStorageName(null);
			allOctionOutList.add(io);
		}
		endMonthMap=this.getInOutBillDOMap(allOctionInList, endMonthMap, 0);//入 调拨
		scs.clearCondition();
		scs.addCondition("logic_wh_check_task.zd009BillType", BillStatusUtil.EVERDAYCHECK);
		scs.addCondition("logic_wh_check_task.zd003TaskStatus",BillStatusUtil.WH_CHECK_TASK_FOUR,SearchCondition.OP_EQUAL);
		scs.addCondition("logic_wh_check_task.bizModifyDate", sdate,BillStatusUtil.OP_INMONTH);
		List<InOutBillDO> pdList=this.excelExportDAO.findPDByConditions(scs);
		List<InOutBillDO> pdOutList= new ArrayList<InOutBillDO>();
		List<InOutBillDO> pdInList= new ArrayList<InOutBillDO>();
		for(InOutBillDO io:pdList){
			if(io.getInQuantity().compareTo(BigDecimal.ZERO)==1){
				pdInList.add(io);
			}
			if(io.getOutQuantity().compareTo(BigDecimal.ZERO)==1){
				pdOutList.add(io);
			}
		}
		endMonthMap=this.getInOutBillDOMap(pdInList, endMonthMap, 0);//入  盘点
		scs.clearCondition();
//		scs=this.getConditionByEndMonth(request, "zd004WhCode", "zd010OtherDate", "logic_warehouse_otherin", "qtr");
		scs=this.getConditionByEndMonth(request, "zd004WhCode", "bizModifyDate", "logic_warehouse_otherin", "qtr");
		scs.addCondition("logic_warehouse_otherin.zd003BillStatus", BillStatusUtil.OTHERWH_BILL_STATUE_FOUR);
		List<InOutBillDO> otherInList= this.excelExportDAO.findOtherInAndItemByConditions(scs);//查询其他入库
		endMonthMap=this.getInOutBillDOMap(otherInList,endMonthMap,0);
		scs.clearCondition();
//		scs=this.getConditionByEndMonth(request, "zd003WhCode", "zd004InDate", "logic_warehouse_batch_in", "fpi");
		scs=this.getConditionByEndMonth(request, "zd003WhCode", "bizModifyDate", "logic_warehouse_batch_in", "fpi");
		scs.addCondition("logic_warehouse_batch_in.zd010Stauts", BillStatusUtil.BATCH_IN_TWO);
		List<InOutBillDO> batchInList=this.excelExportDAO.findBatchInAndItemByConditions(scs);//多pi入库
		endMonthMap=this.getInOutBillDOMap(batchInList,endMonthMap,0);
		scs.clearCondition();
//		scs=this.getConditionByEndMonth(request, "zd006WhCode", "zd013Date", "logic_purchase_ware", "cgr");
		scs=this.getConditionByEndMonth(request, "zd006WhCode", "bizModifyDate", "logic_purchase_ware", "cgr");
		scs.addCondition("logic_purchase_ware.zd004Status", BillStatusUtil.PCSW_BILL_STATUS_FOUR);
		List<InOutBillDO> purWareInList= this.excelExportDAO.findPurchasewareInAndItemByConditions(scs);//查询采购入库
		endMonthMap = this.getInOutBillDOMap(purWareInList,endMonthMap,0);
		scs.clearCondition();
//	    scs=this.getConditionByEndMonth(request, "zd004WhCode", "zd010OtherDate", "logic_production_storagein", "cpr");
		scs=this.getConditionByEndMonth(request, "zd004WhCode", "bizModifyDate", "logic_production_storagein", "cpr");
		scs.addCondition("logic_production_storagein.zd011BillStatus", BillStatusUtil.PROSTORIN_STATUS_FIVE);
		List<InOutBillDO> storogeInList= this.excelExportDAO.findSotrageInAndItemByConditions(scs);//查询成品入库
		endMonthMap = this.getInOutBillDOMap(storogeInList,endMonthMap,0);
		endMonthMap=this.getInOutBillDOMap(allOctionOutList, endMonthMap, 1);//出 调拨
		endMonthMap=this.getInOutBillDOMap(pdOutList, endMonthMap, 1);//出 盘点
		scs.clearCondition();
//		scs=this.getConditionByEndMonth(request, "zd004WhCode", "zd010OtherDate", "logic_warehouse_otherout", "qtc");
		scs=this.getConditionByEndMonth(request, "zd004WhCode", "bizModifyDate", "logic_warehouse_otherout", "qtc");
		scs.addCondition("logic_warehouse_otherout.zd003BillStatus",BillStatusUtil.OTHERWH_BILL_STATUE_FOUR);
		List<InOutBillDO> otherOutList= this.excelExportDAO.findOtherOutAndItemByConditions(scs);//查询其他出库
		endMonthMap= this.getInOutBillDOMap(otherOutList,endMonthMap,1);
		scs.clearCondition();
//		scs=this.getConditionByEndMonth(request, "zd011WhCode", "zd010OtherDate", "logic_warehouse_materialout", "llc");
		scs=this.getConditionByEndMonth(request, "zd011WhCode", "bizModifyDate", "logic_warehouse_materialout", "llc");
		scs.addCondition("logic_warehouse_materialout.zd003BillStatus", BillStatusUtil.MATERIALOUT_BILL_STATUE_FOUR);
		List<InOutBillDO> materialOutList= this.excelExportDAO.findMaterialOutAndItemByConditions(scs);//查询材料出库
		endMonthMap= this.getInOutBillDOMap(materialOutList,endMonthMap,1);
		scs.clearCondition();
//		scs=this.getConditionByEndMonth(request, "zd004WhCode", "zd010OtherDate", "logic_production_storageout", "cpc");
		scs=this.getConditionByEndMonth(request, "zd004WhCode", "bizModifyDate", "logic_production_storageout", "cpc");
		scs.addCondition("logic_production_storageout.zd011BillStatus", BillStatusUtil.PROSTOROUT_STATUS_FIVE);
		List<InOutBillDO> storageOutList= this.excelExportDAO.findstorageOutAndItemByConditions(scs);//查询成品出库
		endMonthMap= this.getInOutBillDOMap(storageOutList,endMonthMap,1);
		scs=this.getConditionByEndMonth(request, "zd001WhCode", "zd011Date", "logic_warehouse_history", "end");
		scs.setRemovedProperty(null);
		List<LogicWarehouseHistoryDO> historyList= this.logicWarehouseHistoryDAO.findListByCondition(scs);//查询所有的历史记录获得期末库存
		endMonthMap=this.getHoistoryMap(historyList,endMonthMap);
		Map<String , BasicMaterialsDO>  materials=oftenMapUtil.getMaterialMapByCode(this.getClearCondition());
		Map<String , BasicMaterialsTypeDO> materialsType=oftenMapUtil.getMaterialTypeById(this.getClearCondition());//类别
		Map<String , BasicMaterialsTypeDO> materialsSeries=oftenMapUtil.getMaterialTypeKeyMaterialCode(this.getClearCondition());//系列
		Map<String, BasicStapleUnitDO> utilsMap=this.oftenMapUtil.getMaterialUtilById(this.getClearCondition());
		Map<String , BasicStorageInfoTestDO> storageInfo=this.oftenMapUtil.getStroageInfoMap(this.getClearCondition());
		//单位map
		for(String key:endMonthMap.keySet()){
			LogicWarehouseEndMonthSumVO endVo=endMonthMap.get(key);
			BasicMaterialsDO material=materials.get(endVo.getZdMaterCode());
			this.getNewLogicWarehouseEndMonthSumVO(materialsType, materialsSeries, utilsMap, endVo,
					material);
			BasicStorageInfoTestDO info=storageInfo.get(endVo.getZdWhName());
			// code name model spec color quanlity storagecode pi
			String keyStr=(StringUtils.isEmpty(endVo.getZdMaterCode())?null:endVo.getZdMaterCode())+"_"+
							(StringUtils.isEmpty(endVo.getZdMaterName())?null:endVo.getZdMaterName())+"_"+
							(StringUtils.isEmpty(endVo.getZdMaterModel())?null:endVo.getZdMaterModel())+"_"+
							(StringUtils.isEmpty(endVo.getZdMaterSpec())?null:endVo.getZdMaterSpec())+"_"+
							(StringUtils.isEmpty(endVo.getZdMaterColor())?null:endVo.getZdMaterColor())+"_"+
							(StringUtils.isEmpty(endVo.getZdMaterQuanlity())?null:endVo.getZdMaterQuanlity())+"_"+
							(StringUtils.isEmpty(info.getZd002Code())?null:info.getZd002Code());

			if(info==null){
				throw new SyBaseException("没有对应的仓库,name="+endVo.getZdWhName());
			}
			if("成品".equals(info.getZd004Nature())){
				endMonth.add(endVo);
			}else{
				LogicWarehouseEndMonthSumVO vo=monthMap.get(keyStr);
				if(vo==null){
					vo=new LogicWarehouseEndMonthSumVO();
				}
				endVo.setZdTaskQuantity((vo.getZdTaskQuantity()==null?BigDecimal.ZERO:vo.getZdTaskQuantity()).
						add(endVo.getZdTaskQuantity()));
				endVo.setZdTaskSumMoney((vo.getZdTaskSumMoney()==null?BigDecimal.ZERO:vo.getZdTaskSumMoney()).
						add(endVo.getZdTaskSumMoney()));
				endVo.setZdInQuantity((vo.getZdInQuantity()==null?BigDecimal.ZERO:vo.getZdInQuantity()).
						add(endVo.getZdInQuantity()));
				endVo.setZdInSumMoney((vo.getZdInSumMoney()==null?BigDecimal.ZERO:vo.getZdInSumMoney()).
						add(endVo.getZdInSumMoney()));
				endVo.setZdOutQuantity((vo.getZdOutQuantity()==null?BigDecimal.ZERO:vo.getZdOutQuantity()).
						add(endVo.getZdOutQuantity()));
				endVo.setZdOutSumMoney((vo.getZdOutSumMoney()==null?BigDecimal.ZERO:vo.getZdOutSumMoney()).
						add(endVo.getZdOutSumMoney()));
				endVo.setZdStockQuantity((vo.getZdStockQuantity()==null?BigDecimal.ZERO:vo.getZdStockQuantity()).
						add(endVo.getZdStockQuantity()));
				endVo.setZdStockSumMoney((vo.getZdStockSumMoney()==null?BigDecimal.ZERO:vo.getZdStockSumMoney()).
						add(endVo.getZdStockSumMoney()));
				if(endVo.getZdTaskQuantity().add(endVo.getZdInQuantity()).compareTo(BigDecimal.ZERO)==1){
					BigDecimal avgPrice=endVo.getZdTaskSumMoney().add(endVo.getZdInSumMoney()).
							divide((endVo.getZdTaskQuantity().add(endVo.getZdInQuantity())),4);
					endVo.setZdOutSumMoney(avgPrice.multiply(endVo.getZdOutQuantity()));//出库金额
					endVo.setZdStockSumMoney(avgPrice.multiply(endVo.getZdStockQuantity()));
					endVo.setZdAvgPrice(avgPrice);
				}else{
					endVo.setZdOutQuantity(BigDecimal.ZERO);
					endVo.setZdStockSumMoney(BigDecimal.ZERO);
					endVo.setZdAvgPrice(BigDecimal.ZERO);
				}
				monthMap.put(keyStr, endVo);
			}
		}
		for(String key:monthMap.keySet()){
			LogicWarehouseEndMonthSumVO endVo=monthMap.get(key);
			BasicMaterialsDO material=materials.get(endVo.getZdMaterCode());
			this.getNewLogicWarehouseEndMonthSumVO(materialsType, materialsSeries, utilsMap, endVo,
					material);
			if(endVo.getZdInQuantity().compareTo(BigDecimal.ZERO)==0){
				if(endVo.getZdOutQuantity().compareTo(BigDecimal.ZERO)==0){
					if(endVo.getZdTaskQuantity().compareTo(BigDecimal.ZERO)==0){
						if(endVo.getZdStockQuantity().compareTo(BigDecimal.ZERO)==0){
							continue;
						}
					}
				}
			}
			endMonth.add(endVo);
		}
		return endMonth;
	}
	private void getNewLogicWarehouseEndMonthSumVO (
			Map<String, BasicMaterialsTypeDO> materialsType,
			Map<String, BasicMaterialsTypeDO> materialsSeries,
			Map<String, BasicStapleUnitDO> utilsMap,
			LogicWarehouseEndMonthSumVO endVo, BasicMaterialsDO material) throws SyBaseException {
		try {
			if(material!=null){
				BasicMaterialsTypeDO type=materialsType.get(material.getZd029MaterTypeId());
				if(type!=null){
					endVo.setZdMaterTypeName(type.getZd002Name());//类别
				}
				BasicStapleUnitDO util=utilsMap.get(material.getZd007Unit());
				if(util!=null){
					endVo.setZdMaterUnit(util.getZd002Name());
				}
			}
			BasicMaterialsTypeDO series=materialsSeries.get(endVo.getZdMaterCode());
			if(series!=null){
				endVo.setZdMaterSery(series.getZd002Name());//系列
			}
			BigDecimal allMoney=(endVo.getZdTaskSumMoney()==null?BigDecimal.ZERO:endVo.getZdTaskSumMoney()).
					add(endVo.getZdInSumMoney()==null?BigDecimal.ZERO:endVo.getZdInSumMoney());
			BigDecimal allQuantity=(endVo.getZdTaskQuantity()==null?BigDecimal.ZERO:endVo.getZdTaskQuantity()).
					add(endVo.getZdInQuantity()==null?BigDecimal.ZERO:endVo.getZdInQuantity());
			BigDecimal avgPrice=BigDecimal.ZERO;
			if(allQuantity.compareTo(BigDecimal.ZERO)==1){
				avgPrice=allMoney.divide(allQuantity, 4);
			}
			endVo.setZdOutSumMoney(avgPrice.multiply(endVo.getZdOutQuantity()==null?BigDecimal.ZERO:endVo.getZdOutQuantity()));//出库金额
			endVo.setZdStockSumMoney(avgPrice.multiply(endVo.getZdStockQuantity()==null?BigDecimal.ZERO:endVo.getZdStockQuantity()));
			endVo.setZdAvgPrice(avgPrice);
			endVo.setZdAvgPrice(((endVo.getZdAvgPrice()==null||endVo.getZdAvgPrice().//平均单价
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdAvgPrice()));
			endVo.setZdTaskQuantity(((endVo.getZdTaskQuantity()==null||endVo.getZdTaskQuantity().//期初数量
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdTaskQuantity()));
			endVo.setZdTaskSumMoney(((endVo.getZdTaskSumMoney()==null||endVo.getZdTaskSumMoney().
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdTaskSumMoney()));
			endVo.setZdInQuantity(((endVo.getZdInQuantity()==null||endVo.getZdInQuantity().
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdInQuantity()));
			endVo.setZdInSumMoney(((endVo.getZdInSumMoney()==null||endVo.getZdInSumMoney().
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdInSumMoney()));
			endVo.setZdOutQuantity(((endVo.getZdOutQuantity()==null||endVo.getZdOutQuantity().
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdOutQuantity()));
			endVo.setZdStockQuantity(((endVo.getZdStockQuantity()==null||endVo.getZdStockQuantity().
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdStockQuantity()));
			endVo.setZdStockSumMoney(((endVo.getZdStockSumMoney()==null||endVo.getZdStockSumMoney().
					compareTo(BigDecimal.ZERO)==0)?BigDecimal.ZERO:endVo.getZdStockSumMoney()));
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(e);
		}
	}

	private Map<String, LogicWarehouseEndMonthSumVO> getEndMonthMap(HttpServletRequest request,
			SearchConditions scs, List<LogicExcelToStoreDO> excelList) {
		Map<String, LogicWarehouseEndMonthSumVO> endMonthMap = new HashMap<String, LogicWarehouseEndMonthSumVO>();
		//获取录入的价格
		Map<String, LogicWarehouseEndMonthSumVO> endMonthPriceMap= new HashMap<String, LogicWarehouseEndMonthSumVO>();
		endMonthPriceMap=this.getExcelMap(excelList,false);
		//选择时间为其他时间的时候  获取盘点表的时间
		scs.clearCondition();
		scs=this.getConditionByEndMonth(request, "zd001WhCode", "zd008StepDate", "logic_wh_check_task", "ct");
		scs.addCondition("logic_wh_check_task.zd009BillType", BillStatusUtil.MONTHCHECK);//月度盘点
		scs.addCondition("logic_wh_check_task.zd003TaskStatus", BillStatusUtil.WH_CHECK_TASK_FOUR);//完结
		//获取导入数据的价格
		List<InOutBillDO> checkTaskList=this.logicWhCheckTaskItemDAO.findCheckTaskList(scs);
		for(InOutBillDO ct:checkTaskList){
			// code name model spec color quanlity storagecode
			String key=(StringUtils.isEmpty(ct.getMaterialCode())?null:ct.getMaterialCode()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialName())?null:ct.getMaterialName()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialModel())?null:ct.getMaterialModel()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialSpec())?null:ct.getMaterialSpec()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialColor())?null:ct.getMaterialColor()) +"_"+
						(StringUtils.isEmpty(ct.getMaterialQuanlity())?null:ct.getMaterialQuanlity()) +"_"+
						(StringUtils.isEmpty(ct.getStorageCode())?null:ct.getStorageCode());
			LogicWarehouseEndMonthSumVO vo= endMonthMap.get(key);
			if(vo==null){
				vo= new LogicWarehouseEndMonthSumVO();
			}
			vo.setZdTaskQuantity(ct.getInQuantity()==null?
					ct.getInQuantity():((vo.getZdTaskQuantity()==null?BigDecimal.ZERO:vo.getZdTaskQuantity()).add(ct.getInQuantity())));
			vo.setZdTaskSumMoney((((endMonthPriceMap.get(key)==null||
					endMonthPriceMap.get(key).getZdTaskSumMoney()==null)?BigDecimal.ZERO:
						endMonthPriceMap.get(key).getZdTaskSumMoney())).
							add(vo.getZdTaskSumMoney()==null?BigDecimal.ZERO:vo.getZdTaskSumMoney()));
			if(vo.getZdTaskQuantity().compareTo(BigDecimal.ZERO)!=0){
				vo.setZdTaskPrice((vo.getZdTaskQuantity()==null||
						vo.getZdTaskQuantity().compareTo(BigDecimal.ZERO)!=0)?BigDecimal.ZERO:(
								vo.getZdTaskSumMoney().divide(vo.getZdTaskQuantity(),4)));
			}else{
				vo.setZdTaskPrice(BigDecimal.ZERO);
			}
			vo.setZdMaterCode(ct.getMaterialCode());
			vo.setZdMaterName(ct.getMaterialName());
			vo.setZdMaterModel(ct.getMaterialModel());
			vo.setZdMaterSize(ct.getMaterialSpec());
			vo.setZdMaterQuanlity(ct.getMaterialQuanlity());
			vo.setZdMaterColor(ct.getMaterialColor());
			vo.setZdWhCode(ct.getStorageCode());
			vo.setZdWhName(ct.getStorageName());
			vo.setZdWhId(ct.getStorageId());
			vo.setZdCompCode(ct.getConsumerName());//客户 or 供应商
			//类别
			vo.setZdMaterUnit(ct.getMaterialUnit());
			vo.setPiCode(ct.getPiCode());
			endMonthMap.put(key, vo);
		}
		return endMonthMap;
	}

	private SearchConditions getClearCondition() {
		SearchConditions scs= new SearchConditions();
		scs.clearCondition();
		scs.removeCondition(null);
		scs.setLimitClause(null);
		scs.setLimitPage(false);
		return scs;
	}


	private Map<String, LogicWarehouseEndMonthSumVO> getHoistoryMap(List<LogicWarehouseHistoryDO> historyList,
			Map<String, LogicWarehouseEndMonthSumVO> endMonthMap) {
		for(LogicWarehouseHistoryDO hs:historyList){
			if(hs==null||hs.getZd009Quantity()==null||hs.getZd009Quantity().compareTo(BigDecimal.ZERO)<=0){
				continue;
			}
			// code name model spec color quanlity storagecode pi
			String keyStr=(StringUtils.isEmpty(hs.getZd002MaterialCode())?null:hs.getZd002MaterialCode())+"_"+
							(StringUtils.isEmpty(hs.getZd002MaterialName())?null:hs.getZd002MaterialName())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialModel())?null:hs.getZd003MaterialModel())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialSpec())?null:hs.getZd003MaterialSpec())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialColor())?null:hs.getZd003MaterialColor())+"_"+
							(StringUtils.isEmpty(hs.getZd003MaterialQuanlity())?null:hs.getZd003MaterialQuanlity())+"_"+
							(StringUtils.isEmpty(hs.getZd001WhCode())?null:hs.getZd001WhCode());
	//						+"_"+(StringUtils.isEmpty(hs.getZd006PiCode())?null:hs.getZd006PiCode());
			LogicWarehouseEndMonthSumVO endMon=endMonthMap.get(keyStr);
			if(endMon==null){
				endMon=new LogicWarehouseEndMonthSumVO();
				endMon.setPiCode(hs.getZd006PiCode());
				endMon.setZdCompName(hs.getZd008CustomerName());
				endMon.setZdMaterCode(hs.getZd002MaterialCode());
				endMon.setZdMaterColor(hs.getZd003MaterialColor());
				endMon.setZdMaterModel(hs.getZd003MaterialModel());
				endMon.setZdMaterName(hs.getZd002MaterialName());
				endMon.setZdMaterQuanlity(hs.getZd003MaterialQuanlity());
				endMon.setZdMaterSize(hs.getZd003MaterialSpec());
				endMon.setZdWhName(hs.getZd001WhName());
				endMon.setZdWhCode(hs.getZd001WhCode());
				endMon.setZdStockQuantity(hs.getZd009Quantity());
			}else{
				endMon.setZdStockQuantity(hs.getZd009Quantity());
			}
			endMonthMap.put(keyStr, endMon);
		}
		return endMonthMap;
	}
	/**
	 * 期初数据
	 * @param excelList
	 * @return
	 */
	private Map<String, LogicWarehouseEndMonthSumVO>  getExcelMap(List<LogicExcelToStoreDO> excelList,boolean isbegin) {
		Map<String, LogicWarehouseEndMonthSumVO> excelMap= new HashMap<String, LogicWarehouseEndMonthSumVO>();
		String msg="出现重复的数据：";
		for(LogicExcelToStoreDO excel:excelList){// code name model spec color quanlity storagecode
			if(excel==null){
				continue;
			}
			String keyStr="";
			if(isbegin){
				keyStr=(StringUtils.isEmpty(excel.getZd001MaterialCode())?null:excel.getZd001MaterialCode())+"_"+//code
						(StringUtils.isEmpty(excel.getZd001MaterialName())?null:excel.getZd001MaterialName())+"_"+//name
						(StringUtils.isEmpty(excel.getZd002MaterialModel())?null:excel.getZd002MaterialModel())+"_"+//model
						(StringUtils.isEmpty(excel.getZd003MaterialSpec())?null:excel.getZd003MaterialSpec())+"_"+//spec
						null+"_"+//color
						(StringUtils.isEmpty(excel.getZd004MaterialTypeName())?null:excel.getZd004MaterialTypeName())+"_"+//quanlity
						(StringUtils.isEmpty(excel.getZd012WareHouseCode())?null:excel.getZd012WareHouseCode());
			}else{
				keyStr=(StringUtils.isEmpty(excel.getZd001MaterialCode())?null:excel.getZd001MaterialCode())+"_"+//code
						(StringUtils.isEmpty(excel.getZd001MaterialName())?null:excel.getZd001MaterialName())+"_"+//name
						(StringUtils.isEmpty(excel.getZd002MaterialModel())?null:excel.getZd002MaterialModel())+"_"+//model
						(StringUtils.isEmpty(excel.getZd003MaterialSpec())?null:excel.getZd003MaterialSpec())+"_"+//spec
						(StringUtils.isEmpty(excel.getZd003MaterialColor())?null:excel.getZd003MaterialColor())+"_"+//color
						(StringUtils.isEmpty(excel.getZd003MaterialQuanlity())?null:excel.getZd003MaterialQuanlity())+"_"+//quanlity
						(StringUtils.isEmpty(excel.getZd012WareHouseCode())?null:excel.getZd012WareHouseCode());
			}

			LogicWarehouseEndMonthSumVO ex= excelMap.get(keyStr);
			if(ex!=null){
				ex.setZdTaskSumMoney((excel.getZd010MaterialEndMoney()==null?BigDecimal.ZERO:excel.getZd010MaterialEndMoney()).add(
						ex.getZdTaskSumMoney()==null?BigDecimal.ZERO:ex.getZdTaskSumMoney()));
				ex.setZdTaskQuantity((excel.getZd010MaterialEndNumber()==null?BigDecimal.ZERO:excel.getZd010MaterialEndNumber()).add(
						ex.getZdTaskQuantity()==null?BigDecimal.ZERO:ex.getZdTaskQuantity()));
				msg=msg+"物料编码为"+ex.getZdMaterCode()+",";
				if(excel.getZd010MaterialEndNumber().compareTo(BigDecimal.ZERO)==0||
						excel.getZd010MaterialEndMoney().compareTo(BigDecimal.ZERO)==0){
					ex.setZdTaskPrice(BigDecimal.ZERO);
				}else{
					ex.setZdTaskPrice(excel.getZd010MaterialEndMoney().divide(excel.getZd010MaterialEndNumber(),4));
				}
			}else{
				ex=new LogicWarehouseEndMonthSumVO();
				ex.setZdWhCode(excel.getZd012WareHouseCode());
				ex.setZdWhName(excel.getZd012WareHouseName());
				ex.setZdCompCode(excel.getZd011ConsumerCode());//客户 or 供应商
				ex.setZdCompName(excel.getZd011ConsumerName());
				ex.setZdMaterTypeName(excel.getZd004MaterialTypeName());//类别
				ex.setZdMaterCode(excel.getZd001MaterialCode());
				ex.setZdMaterName(excel.getZd001MaterialName());
				ex.setZdMaterModel(excel.getZd002MaterialModel());
				ex.setZdMaterSize(excel.getZd003MaterialSpec());
				if(!isbegin){
					ex.setZdMaterColor(excel.getZd003MaterialColor());
					ex.setZdMaterQuanlity(excel.getZd003MaterialQuanlity());
				}else{
					ex.setZdMaterColor(null);
					ex.setZdMaterQuanlity(excel.getZd004MaterialTypeName());//把类别放在了材质里面
				}
				ex.setZdMaterUnit(excel.getZd005MaterialUtil());
				ex.setPiCode(excel.getZd014MaterialPICode());
				ex.setZdTaskPrice(excel.getZd006MaterialPrice());//期初单价
				ex.setZdTaskQuantity(excel.getZd010MaterialEndNumber());
				ex.setZdTaskSumMoney(excel.getZd010MaterialEndMoney());
			}
			excelMap.put(keyStr, ex);
		}
		return excelMap;
	}

	private Map<String, LogicWarehouseEndMonthSumVO> getInOutBillDOMap(List<InOutBillDO> list ,
			Map<String, LogicWarehouseEndMonthSumVO> endMonMap , int stauts){
/*		String errorMsgOne="没 期初，没入库，有出库的错误数据:";
		String errorMsgTwo="出库数大于入库与期初的错误数据: ";
*/		for(InOutBillDO io:list){
			if(io==null){
				continue;
			}
			// code name model spec color quanlity storagecode pi
			String key=(StringUtils.isEmpty(io.getMaterialCode())?null:io.getMaterialCode())+"_"+
						(StringUtils.isEmpty(io.getMaterialName())?null:io.getMaterialName())+"_"+
						(StringUtils.isEmpty(io.getMaterialModel())?null:io.getMaterialModel())+"_"+
						(StringUtils.isEmpty(io.getMaterialSpec())?null:io.getMaterialSpec())+"_"+
						(StringUtils.isEmpty(io.getMaterialColor())?null:io.getMaterialColor())+"_"+
						(StringUtils.isEmpty(io.getMaterialQuanlity())?null:io.getMaterialQuanlity())+"_"+
						(StringUtils.isEmpty(io.getStorageCode())?null:io.getStorageCode());
			LogicWarehouseEndMonthSumVO end= endMonMap.get(key);
			if(0==stauts){//入库
				if(end==null){//第一次入
					end=new LogicWarehouseEndMonthSumVO();
					end.setZdWhCode(io.getStorageCode());
					end.setZdWhName(io.getStorageName());
					end.setZdMaterCode(io.getMaterialCode());
					end.setZdMaterName(io.getMaterialName());
					end.setZdMaterModel(io.getMaterialModel());
					end.setZdMaterSize(io.getMaterialSpec());
					end.setZdMaterColor(StringUtils.isEmpty(io.getMaterialColor())?null:io.getMaterialColor());
					end.setZdMaterQuanlity(io.getMaterialQuanlity());//把类别放在了材质里面
					end.setZdMaterUnit(io.getMaterialUnit());
					end.setPiCode(io.getPiCode());
					//第一次
					end.setZdInQuantity(io.getInQuantity()==null?BigDecimal.ZERO:io.getInQuantity());
					end.setZdInSumMoney((io.getAllMoney()==null?BigDecimal.ZERO:io.getAllMoney()));
				}else{//重复录入
					end.setZdInQuantity((io.getInQuantity()==null?BigDecimal.ZERO:io.getInQuantity()).add(
							(end.getZdInQuantity()==null?BigDecimal.ZERO:end.getZdInQuantity())));
					end.setZdInSumMoney((io.getAllMoney()==null?BigDecimal.ZERO:io.getAllMoney()).add(
							end.getZdInSumMoney()==null?BigDecimal.ZERO:end.getZdInSumMoney()));
				}
				endMonMap.put(key, end);
			}else if(1==stauts){//出库
				BigDecimal inNum=end==null?BigDecimal.ZERO:(end.getZdInQuantity()==null?BigDecimal.ZERO:end.getZdInQuantity());
				BigDecimal avgInPrice=(inNum.compareTo(BigDecimal.ZERO)<1)?BigDecimal.ZERO:
					((end==null||end.getZdInSumMoney()==null||end.getZdInSumMoney().compareTo(BigDecimal.ZERO)<1)?
							BigDecimal.ZERO:end.getZdInSumMoney().divide(inNum,4));
				if(end==null){//没记录的数据 （在系统调试期间存在着不确定性(没有入 没有期初 但是有出库)）
					LogicWarehouseEndMonthSumVO endNull=new LogicWarehouseEndMonthSumVO();
					endNull.setZdWhCode(io.getStorageCode());
					endNull.setZdWhName(io.getStorageName());
					endNull.setZdMaterCode(io.getMaterialCode());
					endNull.setZdMaterName(io.getMaterialName());
					endNull.setZdMaterModel(io.getMaterialModel());
					endNull.setZdMaterSize(io.getMaterialSpec());
					endNull.setZdMaterColor(StringUtils.isEmpty(io.getMaterialColor())?null:io.getMaterialColor());
					endNull.setZdMaterQuanlity(io.getMaterialQuanlity());//把类别放在了材质里面
					endNull.setZdMaterUnit(io.getMaterialUnit());
					endNull.setPiCode(io.getPiCode());//一致
					endNull.setZdCompName(io.getConsumerName());
					endNull.setZdOutQuantity(io.getOutQuantity());
					endNull.setZdOutSumMoney(io.getOutQuantity().multiply(avgInPrice));
					endNull.setZdAvgPrice(avgInPrice);
					endMonMap.put(key, endNull);
				}else{
					end.setZdOutQuantity((end.getZdOutQuantity()==null?BigDecimal.ZERO:end.getZdOutQuantity()).add(
								(io.getOutQuantity()==null?BigDecimal.ZERO:io.getOutQuantity())));
					end.setZdOutSumMoney(end.getZdOutQuantity()
							.multiply(avgInPrice));
					endMonMap.put(key, end);
				}
			}
		}
		return endMonMap;
	}
	/**
	 * @param request
	 * @param whCode 仓库字段名称
	 * @param field 确认建单的时间
	 * @param type 类型  其他入库 qtr  其他出库  qtc cgr 。。。
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private  SearchConditions getConditionByEndMonth(HttpServletRequest request,
			String whCode , String field,String tableName,String type) {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs= new SearchConditions();
		hander.getWheres(scs);
		try {
			hander.setFilters(new String(request.getParameter("filters").getBytes(
					"ISO-8859-1"), "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		scs.clearCondition();
		hander.getWheres(scs);
		Collection<SearchCondition> condition=scs.getConditions();
		boolean isok=true;
		for(SearchCondition sc:condition){
			if(StringUtils.isNotBlank(sc.getField())){
				if(sc.getField().equals("date")){//建单时间查询
					sc.setField(field);
					sc.setOperator(BillStatusUtil.OP_INMONTH);
				}
				if(sc.getField().equals("whcode")){
					sc.setField(whCode);
				}
				if("excel".equals(type)){

				}else if("qtr".equals(type)){

				}else if("cgr".equals(type)){

				}else if("cpr".equals(type)){

				}else if("qtc".equals(type)){

				}else if("llc".equals(type)){

				}else if("cpc".equals(type)){

				}else if("end".equals(type)){

				}else if("ct".equals(type)){

				}else if("db".equals(type)){

				}else if("pd".equals(type)){

				}else if("fpi".equals(type)){

				}else{
					throw new SyBaseException("没有这个类型");
				}

				String[] fieldArr=sc.getField().split(".");
				if(fieldArr.length>0){
					sc.setField(tableName+"."+fieldArr[fieldArr.length-1]);
				}else{
					sc.setField(tableName+"."+sc.getField());
				}
			}
			if(sc.getOperator().equals(SearchCondition.OP_GREATER)||sc.getOperator().equals(SearchCondition.OP_SMALLER)||sc.getOperator().equals(BillStatusUtil.OP_INMONTH)){
				isok=false;
			}
		}
		if(isok){
			scs.addCondition(new SearchCondition(field, BillStatusUtil.OP_INMONTH, new SimpleDateFormat("yyyyMM").format(new Date())));
		}
		Map<String,Object> sqlWHMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,whCode);
		scs.addCondition(sqlWHMap.get("option")+"",(List<String>)sqlWHMap.get("roleWhList"));
		scs.setLimitClause(null);
		scs.setLimitPage(false);
		return scs;
	}

}
